#!/usr/bin/php
<?php

if(count($argv) != 2  || in_array('-h', $argv) || in_array('--help', $argv)) {
	echo "Upload an entire folder structure to SmugMug\n",
	"Usage: multi-album-upload folder\n\n",
	"Required Stucture:\n",
	"Base Folder\n",
	"\tCategory 1\n",
	"\t\tAlbum 1\n",
	"\t\tAlbum 2\n",
	"\tCategory 2\n",
	"\t\tAlbum 3\n";
	die();
}

require_once('includes/utility.php');

//Setup stat variables
$categoriesAdded = 0;
$albumsAdded = 0;
$filesAdded = 0;
$filesReplaced = 0;
$filesMDUpdated = 0;
$filesSkipped = 0;


//Begin processing things
$l->status("Determining file structure...");
$structure = get_local_structure($argv[1]);
$l->done();

try{
	$l->status("Fetching category list from server");
	$categories = $s->categories_get();
	$l->done();

	$l->status("Fetching album list from server");
	$serverAlbums = $s->albums_get("Heavy=1");
	$l->done();

	foreach($structure as $category=>$albums){
		$l->heading("Category: {$category}");

		//Check to see if the category already exists
		$serverCat = false;
		foreach($categories as $cat){
			if($cat['Name'] == $category){
				$serverCat = $cat;
				break;
			}
		}

		//If it doesn't we need to create it
		if(!$serverCat){
			$l->status("Creating category");
			$serverCat['id'] = $s->categories_create("Name={$category}");
			$serverCat['Name'] = $category;
			$l->done();
			$categoriesCreated++;
		}

		//Start working on albums
		foreach($albums as $album=>$files){
			$l->heading("Album: {$album}");

			//Check if album exists
			$serverAlbum = false;
			foreach($serverAlbums as $sa){
				if($sa['Title'] == $album && $sa['Category']['id'] == $serverCat['id']){
					$serverAlbum = $sa;
					break;
				}
			}

			//Create the album if it doesn't exist
			if(!$serverAlbum){
				$l->status("Creating album");
				$serverAlbum = $s->albums_create("Title={$album}", "CategoryID={$serverCat['id']}");
				$serverAlbum = $s->albums_getInfo("AlbumID={$serverAlbum['id']}", "AlbumKey={$serverAlbum['Key']}");
				$l->done();
				$albumsCreated++;
			}

			//Download image information for the album if it is available
			$images = array();
			if($serverAlbum['ImageCount'] > 0){
				$l->status("Downloading image information from album");
				$albumImages = $s->images_get("AlbumID={$serverAlbum['id']}", "AlbumKey={$serverAlbum['Key']}", "Heavy=1");
				$albumImages = $albumImages['Images'];
				if(!empty($albumImages)){
					foreach($albumImages as $image){
						$images[$image['FileName']] = $image;
					}
				}
				$l->done();
			}else{
				$l->writeLine("Album is currently empty");
			}

			//Start dealing with files
			$l->status("Preparing files");
			$uploads = array();
			foreach($files as $file){
				$uploads[] = prepare_file($file);
				$count++;
				if($count % 50 == 0){
					echo ".";
				}
			}
			$l->done();

			foreach($uploads as $upload){
				// If an image with the same filename has already been uploaded
				if($images[$upload['filename']]){
					//Make life a lot easier
					$image = $images[$upload['filename']];

					// Check if the md5 is different
					if(needUpdate($image, $upload)){
						$l->status("Replacing {$upload['filename']} (ID:{$image['id']})");
						$s->images_upload("AlbumID={$serverAlbum['id']}", "File={$upload['path']}", "ImageID={$image['id']}");
						$filesReplaced++;
						$l->queued();

						// Replace the metadata if we need to
						if($image['Caption'] != $upload['caption'] || $image['Keywords'] != $upload['keywords']){
							$l->indent();
							$l->status("Updating Metadata");
							$s->images_changeSettings("ImageID={$image['id']}", "Caption={$upload['caption']}", "Keywords={$upload['keywords']}");
							$filesMDUpdated++;
							$l->done();
							$l->endSection();
						}
					}else{
						//$l->writeLine("Skipping {$upload['filename']}");
						$filesSkipped++;
					}
				}else {
					$l->status("Adding {$upload['filename']}");
					$s->images_upload("AlbumID={$serverAlbum['id']}", "File={$upload['path']}");
					$filesAdded++;
					$l->queued();
				}
			}

			$l->status('Processing Adds/Replaces');
			$s->batchUpload();
			$l->done();

			if($s->deleteAllowed($album)) {
				$l->heading('Deleting orphan images from SmugMug');
				$files = array();
				$deletes = array();

				// Put the local files into a nice, easy to parse array
				foreach($uploads as $u) {
					$files[] = $u['filename'];
				}

				// Delete orphaned files
				foreach($images as $i) {
					if(!in_array($i['FileName'], $files)) {
						$l->status($i['FileName']);
						$s->images_delete("ImageID={$i['id']}");
						$l->done();
					}
				}
				$l->endSection();
			}

			$l->endSection(); // End the album section
		}
		
		$l->endSection();
	}

}catch(Exception $e){
	echo $e->__toString();
}

$failed = $s->getFailed();
if(!empty($failed)) {
	$l->heading("Failed Uploads");
	foreach($failed as $file) {
		$l->writeLine("{$file['file']}: " . print_r($file['message'], true));
	}
}

echo "\nSummary\n";
echo "=========================================\n";
echo "Categories Created: {$categoriesAdded}\n";
echo "Albums Created: {$albumsAdded}\n";
echo "Images Added: {$filesAdded}\n";
echo "Images Replaced: {$filesReplaced}\n";
echo "Metadata Updated: {$filesMDUpdated}\n";
echo "Files Skipped: {$filesSkipped}\n";
echo "=========================================\n\n";